package day13;

import java.util.concurrent.*;

//自定义线程池
public class MyThreadPool {
    //提供七大核心参数的属性
    //1.定义核心线程数 如果是单线程池 核心数量就是1 记住不可变
    private final int core_num=10;
    //2.最大线程数
    private final int max_num=100;
    //3.定义存活时间
    private final long alive_time=30;
    //4.定义时间单位
    private final TimeUnit unit=TimeUnit.SECONDS;//秒 枚举常量TimeUnit
    //5.定义工作队列(任务队列)
    private final BlockingQueue<Runnable> queue=new  ArrayBlockingQueue(core_num);
    //6.定义线程工厂
    private final ThreadFactory factory= Executors.defaultThreadFactory();
    //7.拒绝策略
    private final RejectedExecutionHandler handler=
            new ThreadPoolExecutor.AbortPolicy();
    //8.定义线程池对象 利用上面七个参数
    //再利用ThreadPoolExecutor构造方法 来创建线程池
    private final ExecutorService pool;
    public MyThreadPool(){
        pool=new ThreadPoolExecutor(
                core_num, max_num,alive_time,unit,queue,factory,handler
        );
    }
    //再提供线程池添加任务的方法execute (Runnable) (Callable)
    //返回true 执行任务成功 否则为false
    public boolean execute(Runnable r){
        try {
            pool.execute(r);
            return true;
        }catch (Exception e){
            System.out.println("失败");
            return false;
        }
    }
    //提供一个execute(Callable)  方法的重载
    //定义自定义泛型 后面使用泛型
    public <S> Future<S> execute(Callable<S> c){
        Future f= null;
        try {
            f = pool.submit(c);
        } catch (Exception e) {
            System.out.println("失败");
        }
        return f;
    }
    public void shutdown(){
        pool.shutdown();
    }
}
class TestPool{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.创建线程池
        MyThreadPool mtp=new MyThreadPool();
        //2.执行任务
        for(int i=0;i<10;i++){
//        mtp.execute(()->{
//            System.out.println(Thread.currentThread().getName());
//        });
        Future<Long> f= mtp.execute(()->{
            Thread t=Thread.currentThread();
            System.out.println(t.getName());
            return t.getId();
        });
        Long result=f.get();
        System.out.println("Callable结果:"+result);
    }
        //3.关闭
        mtp.shutdown();
    }
}